<template>
  <div class="departments-container">
    <div class="app-container">
      <el-card>
        <!-- 用一个行列布局 -->
        <el-row
          type="flex"
          justify="space-between"
          align="middle"
          style="height: 40px"
        >
          <el-col :span="20">
            <span>江苏传智播客教育科技股份有限公司</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <!-- 两个内容 -->
              <el-col>负责人</el-col>
              <el-col>操作</el-col>
            </el-row>
          </el-col>
        </el-row>
        <!-- tree 布局 -->
        <el-tree :data="list" :props="defaultProps" default-expand-all>
          <!-- 作用域插槽 data拿到的是每一个子节点的对象 -->
          <template #default="{ data }">
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
              style="height: 40px; width: 100%"
            >
              <el-col :span="20">
                <span>{{ data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex" justify="end">
                  <!-- 两个内容 -->
                  <el-col>{{ data.manager }}</el-col>
                  <el-col>
                    <!-- 下拉菜单 element -->
                    <el-dropdown>
                      <span> 操作<i class="el-icon-arrow-down"></i> </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="addDepart(data.id)"
                          >添加子部门</el-dropdown-item
                        >
                        <el-dropdown-item @click.native="editDepart(data.id)"
                          >编辑部门</el-dropdown-item
                        >
                        <el-dropdown-item @click.native="deleteDepart(data.id)"
                          >删除部门</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- @dialog 关闭的回调	 -->
    <el-dialog
      title="提示"
      :visible="dialogVisible"
      width="30%"
      @close="closeDialog"
      @open="openDialog"
    >
      <el-form ref="addForm" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="部门名称" prop="name">
          <el-input
            v-model="form.name"
            style="width: 80%"
            placeholder="1-50个字符"
          />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input
            v-model="form.code"
            style="width: 80%"
            placeholder="1-50个字符"
          />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select
            v-model="form.manager"
            style="width: 80%"
            placeholder="请选择"
          >
            <!--
              key: 和v-for配合
              label: 下拉时显示的中文文案
              value：选中某一项时自动绑定到select v-model的数据 通常这个value需要和后端交互
              作为接口数据提交给后端
             -->
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            v-model="form.introduce"
            style="width: 80%"
            placeholder="1-300个字符"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <!-- '@click' should be on a new line.eslintvue/max-attributes-per-line -->
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartments, addDepartments, delDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
// 处理函数
// arr 平铺的没有处理的数组
function totree (arr) {
  const newArr = []
  const map = {}
  arr.forEach(item => {
    if (!item.children) item.children = []
    map[item.id] = item // 添加对应的映射关系
  })
  // console.log(arr)
  // console.log(map)
  arr.forEach(item => {
    if (map[item.pid]) {
      map[item.pid].children.push(item)
    } else {
      newArr.push(item)
    }
  })
  // 处理之后的tree数组
  return newArr
}
export default {
  data () {
    return {
      list: [],
      defaultProps: {
        manager: '张三',
        label: 'name',
        children: 'children'
      },
      dialogVisible: false,
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      managerList: [],
      curId: null
    }
  },
  mounted () {
    this.fetchDepartmentList()
  },
  methods: {
    async fetchDepartmentList () {
      const res = await getDepartments()
      // console.log(res.data.depts)
      this.list = totree(res.data.depts)
    },
    // 点击添加部门打开提示框
    addDepart (id) {
      this.curId = id
      this.dialogVisible = true
    },
    // 删除按钮
    deleteDepart (id) {
      delDepartments(id)
      this.dialogVisible = false // 关闭弹框
      this.fetchDepartmentList() // 获取更新的数据渲染到页面上
    },
    // 点击X、提示框以外 关闭提示框
    closeDialog () {
      this.dialogVisible = false
      // 清除校验痕迹
      this.$refs.addForm.resetFields()
      this.form = { // 清空输入框，给用户好的体验
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    async openDialog () {
      const res = await getEmployeeSimple()
      console.log(res)
      this.managerList = res.data
    },
    confirm () {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          // 登录操作
          try {
            // await addDepartments({
            //   ...this.form,
            //   pid: this.curId
            // })
            if (this.form.id) {
              // 调用更新接口
              await updateDepartments(this.form)
            } else {
              await addDepartments({
                ...this.form,
                pid: this.curId // 这里要的是 你给谁添加子部门就把它的id放过来
              })
            }
            this.fetchDepartmentList() // 获取更新的数据渲染到页面上
            // this.$message.success('新增部门成功') // 提示
            this.$message.success(`${this.form.id ? '更新' : '新增'}部门成功`)
            this.closeDialog()
          } catch (err) {
            console.log(err)
          }
        }
      })
    },
    cancel () {
      // 清空表单 关闭弹层 询问用户确定要退出[大表单且输入的内容很麻烦的场景下需要提示]
      this.closeDialog()
    },
    async editDepart (id) {
      // 1. 弹框的打开
      this.dialogVisible = true
      // 2. 数据的回显 使用当前的id调用详情接口 -> 交给this.form
      const res = await getDepartDetail(id)
      this.form = res.data
    }
  }
}
</script>

<style lang="scss" scoped></style>
